Flutter 访问API

安装http

1
flutter pub add http

无参数请求

1
2
import 'package:http/http.dart' as http;
http.post(Uri.parse('https://xxx.com/aa'));

添加Header或者Cookie

1
2
3
4
5
http.post(Uri.parse('https://xxx.com/aa'),
    headers:{
        'Content-Type':'application/json; charset=UTF-8',
        'Cookie':cookie
    },);

添加数据

1
2
3
4
5
6
http.post(Uri.parse('https://xxx.com/aa'),
    headers:{
        'Content-Type':'application/json; charset=UTF-8',

    },
    body:jsonEncode(form));

Model类转JSON和序列化

手动转换

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class User {
  final String name;
  final String email;

  User(this.name, this.email);

  // fromJson 来序列化JSON
  User.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        email = json['email'];

  // toJson 来将Model类转为Json格式
  Map<String, dynamic> toJson() => {
        'name': name,
        'email': email,
      };
}

当你的项目变大时,手动解码表现得并不理想。手动编写解码逻辑会变得难以管理并容易出错。如果你产生了笔误去获取一个不存在的 JSON 字段,你的代码会在运行时抛出一个错误。

使用json_serializable创建Model类

安装依赖

pubspec.yaml

1
2
3
4
5
6
7
8
dependencies:
  # Your other regular dependencies here
  json_annotation: <latest_version>

dev_dependencies:
  # Your other dev_dependencies here
  build_runner: <latest_version>
  json_serializable: <latest_version>
user.dart
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import 'package:json_annotation/json_annotation.dart';

// 必须包含
// 工具生成的文件
part 'user.g.dart';

@JsonSerializable()
class User {
  User(this.name, this.email);

  // 可以对JSON数据进行重映射,使用JsonKey(name:json中的字段名)
  @JsonKey(name:'Name')
  String name;
  String email;

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);

  Map<String, dynamic> toJson() => _$UserToJson(this);
}

生成代码
1
flutter pub run build_runner build

sdk版本过低时需要将pubspec.yaml中版本升级,再运行生成文件,结束后再恢复之前版本

pubspec.yaml

1
2
3
environment:
  # sdk: ">=2.14.0 <3.0.0"
  sdk: ">=2.7.0 <3.0.0"